var urlPrefix = '/hs_mng/';
var form = document.getElementById('searchForm');
var searchForm = (function() {
	if (location.search) {
		//获取URL中的GET字符串,并转为数组
		var search = decodeURIComponent(location.search.substr(1).replace(/\+/g, "%20")).split('&');
		for (var i = 0; i < search.length; i++) {
			var item = search[i].split('=');
			// 将各项的值设置到表单中
			if (form[item[0]]) {
				if (form[item[0]].type === 'checkbox') {
					form[item[0]].checked = true;
				} else {
					form[item[0]].value = item[1];
				}
			}
		}
	}
	// 选择'每页显示'
	if (form.pagesize) {
		form.pagesize.onchange = function() {
			form.submit();
		};
	}
	// 点击排序
	[].forEach.call(document.querySelectorAll('th .sort'), function(e) {
		e.addEventListener('click', function() {
			form.order.value = this.dataset.order;
			form.sort.value = Number(Number(form.sort.value) === 0); // sort的值为原来的值反转
			document.body.style.cursor = 'progress';
			form.submit();
		});
	});

})();
// 搜索表单按钮对象
var fBtns = (function() {
		var $btns = null;

		function init() {
			$btns = $('<li></li>').appendTo('#searchFormButtons').css({
				float: 'right',
				marginRight: '10%',
			})
		}
		return {
			addBtn: function(fn) {
				if ($btns === null) {
					init();
				};
				var $btn = $('<button></button>').prop({
					class: 'scbtn',
					type: 'button',
				}).appendTo($btns);
				if (typeof fn === 'function') {
					fn($btn);
				}
			}
		}

	})()
	// 表格对象
var table = (function() {
	var $table = $('.tablelist');
	var $thead = $table.find('thead tr');
	var $tbody = $table.find('tbody tr');
	var $btn = null;
	var $checkbox = null;
	return {
		$thead: $thead,
		$tbody: $tbody,
		createBtn: function() {
			if (null === $btn) {
				$btn = $('<button></button>').prop({
					class: 'ibtn',
					type: 'button',
				});
			}
			return $btn.clone(true);
		},
		createCheckbox: function() {
			if (null === $checkbox) {
				$checkbox = $('<input>').prop({
					type: 'checkbox',
				});
			}
			return $checkbox.clone(true);
		},
		/**
		 * 增加多列
		 * @param array cols 每一列配置
		 *      cols数组中元素为对象,如下
		 *      {
		 *      	index:int,//插入位置,
		 *      		// 正数为从左方查找该列插入到该列前方,
		 *      		// 负数为从右方查找该列并插入到该列后方
		 *      	th:function($th){},// th项的回调函数
		 *      		// $th = $('<th></th>');
		 *      	td:function($td,$tr,trData){},//每一行中td项的回调函数
		 *      		// $td = $('<td></td>')
		 *      		// $tr为该行jQuery对象
		 *      		// trData为html中挂载在该tr中的data属性(如:data-id="1")
		 *      }
		 */
		addCols: function(cols) {
			function insert($list, index, $new, insertBefore) {
				if (insertBefore) {
					$new.insertBefore($list.eq(index));
				} else {
					$new.insertAfter($list.eq(index));
				}
			}
			// 处理th及每一列的位置计算
			var $thList = $thead.children();
			cols.forEach(function(col) {
				var index = col.index === undefined ? -1 : col.index;
				var insertBefore = true;
				if (index < 0) {
					insertBefore = false;
					var len = $thList.length;
					if (index === -1) {
						index = len - 1;
					} else {
						index = len + index + 1;
					}
				}
				col.index = index;
				col.insertBefore = insertBefore;

				var $th = $('<th></th>');
				insert($thList, index, $th, insertBefore);
				if (typeof col.th === "function") {
					col.th($th);
				};
			});
			$tbody.each(function(trIndex, tr) {
				var $tr = $(tr);
				var $tdList = $tr.children();
				cols.forEach(function(col) {
					var $td = $('<td></td>');
					insert($tdList, col.index, $td, col.insertBefore);
					if (typeof col.td === "function") {
						col.td($td, $tr, $tr.data());
					}
				});
			});
		},
	}
})();

function getThIndexByText(text) {
	return Number($('.tablelist th:contains("' + text + '")').index());
};

var winOpen = (function() {
	var wins = [];
	return function(url, id, width, height, top, left) {
		if (!wins[id] || wins[id].closed) {
			var width = width || 720;
			var height = height || 600;
			var top = top || 200;
			var left = left || 200;
			var cfg = 'width=' + width + ',height=' + height + ',top=' + top + ',left=' + left;
			wins[id] = window.open(url, '', cfg);
		} else {
			wins[id].focus();
		}
	}
})();

var API = {
	urls: {
		presrent: urlPrefix + 'user/presrent',
	},
	fetch: function(url, data, method) {
		var url = API.urls[url] || url;
		var method = method || 'post';
		return $.ajax({
			url: url,
			method: method,
			data: data,
		});
	},
	checkResponse: function(rtn) {
		try {
			var rtn = JSON.parse(rtn);
		} catch (e) {
			alert('网络错误');
			return false;
		}

		if (rtn.error === undefined) {
			alert('请求错误');
			return false;
		}

		if (rtn.error !== 0) {
			alert(rtn.msg);
			return false;
		}

		return rtn;

	},
};
/**
 * 弹出提示框
 */
function TipsBox() {
	// header
	var $header = $('<div></div>').prop({
		class: 'tiptop'
	});
	var $title = $('<span></span>');
	var $cancelBtn = $('<a></a>').on('click', function() {
		$box.fadeOut(200);
	});
	$header.append($title, $cancelBtn);
	// body
	$body = $('<div></div>').prop({
		class: 'tipinfo'
	});
	$ul = $('<ul></ul>').prop({
		class: 'forminfo'
	}).appendTo($body);
	// box
	var $box = $('<div></div>').prop({
		class: 'tip'
	}).append($header, $body).appendTo($('body'));

	this.title = function(title) {
		$title.text(title);
		return this;
	};
	this.show = function() {
		$box.css({
			top: $(document).scrollTop() + 50 + 'px',
		}).fadeIn(200);
		$(window).on('scroll', function() {
			setTimeout(function() {
				$box.css({
					top: $(document).scrollTop() + 50 + 'px',
				});
			}, 200);

		})
	};
	this.hide = function() {
		$box.fadeOut(200);
	}
	this.createInput = function(prop) {
		var prop = prop || {};
		prop.type = prop.type || 'text';
		prop.class = prop.class || 'scinput';
		var $input;
		if (prop.type == 'textarea') {
			$input = $('<textarea></textarea>');
		} else {
			$input = $('<input/>');
		}
		$input.prop(prop);
		return $input;
	};
	this.createButton = function(text, prop) {
		var prop = prop || {};
		prop.type = prop.type || 'button';
		prop.class = prop.class || 'btn';
		var $button = $('<button></button').prop(prop).text(text);
		return $button;
	};
	this.addLi = function(label, elements) {
		var $li = $('<li></li>').append('<label>' + label + '</label>');
		for (var i = 0; i < elements.length; i++) {
			$li.append(elements[i]);
		}
		$li.appendTo($ul);
		return this;
	};
}

// function userCtrl() {
// 	var index = {
// 		uid : getThIndexByText('用户ID'),
// 	}
// 	// 设置"用户ID"列宽度
// 	table.$thead.find('th').eq(index.uid).width(60);
// 	// 增加'操作'列
// 	table.addCols([{
// 		index: -1,
// 		th: function($th) {
// 			$th.text('操作');
// 		},
// 		td: function($td, $tr) {
// 			var $tdList = $tr.find('td');
// 			var user = {
// 				id: Number($tdList.eq(index.uid).text()),
// 			};
// 			// 查看用户详情
// 			var url = urlPrefix + 'user/detail?uid=' + user.id;
// 			table.createBtn().text('更多操作').appendTo($td)
// 			.on('click', function() {
// 				winOpen(url);
// 			})
// 		}
// 	}]);
// 	// "合并用户"按钮
// 	fBtns.addBtn(function($btn) {
// 		$btn.text('合并用户').on('click', function() {
// 			var url = urlPrefix + 'user/combine';
// 			var winID = 'userCombine';
// 			winOpen(url, winID, '1000');
// 		});
// 	});
// }
/**
 * 用户列表控制器
 */
function userCtrl() {
	var index = {};
	index.uid = getThIndexByText('用户ID');
	index.nickname = getThIndexByText('用户昵称');
	index.balance = getThIndexByText('可用余额');
	// 赠送水费提示框
	var PresrentBox = (function(uid) {
		var user = {};
		var $box = new TipsBox();
		// 创建"用户昵称"标签
		var $nickname = $('<label></label>');
		// 创建"赠送金额"输入框
		var $amount = $box.createInput({
			name: 'amount',
			type: 'number',
			value: 0,
			min: 0,
		});
		var $fen = $('<i>分</i>');
		var $yuan = $('<i class="amount"> 0.00 元</i>').css({
			color: 'darkorange'
		});

		function onAmountChange() {
			var amount = parseInt($amount.val());
			$amount.val(amount);
			amount = isNaN(amount) ? 0 : amount;
			$yuan.text(' ' + (amount / 100).toFixed(2) + ' 元');
		};
		$amount.on('keyup', onAmountChange).on('change', onAmountChange);
		// 创建"赠送理由"输入框
		var $reason = $box.createInput({
			name: 'reason',
			type: 'textarea',
			placeholder: '不超过50个字',
		});
		// 创建"确认按钮"
		$confirmBtn = $box.createButton('赠送').on('click', function() {
			var amount = parseInt($amount.val());
			var reason = $.trim($reason.val());
			if (amount <= 0) {
				alert('赠送金额必须大于0');
				return false;
			};
			if (reason.length > 50) {
				alert('赠送理由不得超过50字');
				$reason.val(reason.substr(0, 50));
				return false;
			};

			var msg = "确定赠送 " + (amount / 100).toFixed(2) + " 元给用户【" + user.nickname + "】\r\n理由:" + reason;

			if (!confirm(msg)) {
				$box.hide();
				return false;
			}

			var post = {
				uid: user.id,
				amount: amount,
				reason: reason,
			}
			var url = urlPrefix + 'user/presrent';
			$.post(url, post, function(rtn) {
				var rtn = API.checkResponse(rtn);
				if (rtn.error === 0) {
					alert('赠送成功');
					location.reload();
				}
				$box.hide();
			});
		});
		// 组建box
		$box.title('赠送水费')
			.addLi('用户', [$nickname])
			.addLi('赠送金额', [$amount, $fen, $yuan])
			.addLi('赠送理由', [$reason])
			.addLi('&nbsp;', [$confirmBtn]);
		return {
			show: function(_user) {
				user = _user
				$nickname.text(user.nickname);
				$box.show();
			},
		};
	})();
	// 增加'操作'列
	table.addCols([{
		index: -1,
		th: function($th) {
			$th.text('操作')
		},
		td: function($td, $tr) {
			var $tdList = $tr.find('td');
			var user = {
				id: Number($tdList.eq(index.uid).text()),
				nickname: $.trim($tdList.eq(index.nickname).text()),
			};
			// 查看用户详情
			(function($td, table) {
				var url = urlPrefix + 'user/detail?uid=' + user.id;
				var $btnList = $('<div>').appendTo($td).addClass('vBtnList');

				var $firstBtn = table.createBtn().text('更多操作').appendTo($td).appendTo($btnList)
					.on('click', function() {
						winOpen(url);
					})
			})($td, table)

			table.createBtn().text('赠送').appendTo($td).on('click', function() {
				PresrentBox.show(user);
			});
		}
	}]);
	// "合并用户"按钮
	fBtns.addBtn(function($btn) {
		$btn.text('合并用户').on('click', function() {
			var url = urlPrefix + 'user/combine';
			var winID = 'userCombine';
			winOpen(url, winID, '1000');
		});
	});
}
/**
 * 用户列表控制器(废弃)
 */
function userCtrl2() {
	var index = {};
	index.uid = getThIndexByText('用户ID');
	index.nickname = getThIndexByText('用户昵称');
	index.balance = getThIndexByText('可用余额');
	// 赠送水费提示框
	var PresrentBox = (function(uid) {
		var user = {};
		var $box = new TipsBox();
		// 创建"用户昵称"标签
		var $nickname = $('<label></label>');
		// 创建"赠送金额"输入框
		var $amount = $box.createInput({
			name: 'amount',
			type: 'number',
			value: 0,
			min: 0,
		});
		var $fen = $('<i>分</i>');
		var $yuan = $('<i class="amount"> 0.00 元</i>').css({
			color: 'darkorange'
		});

		function onAmountChange() {
			var amount = parseInt($amount.val());
			$amount.val(amount);
			amount = isNaN(amount) ? 0 : amount;
			$yuan.text(' ' + (amount / 100).toFixed(2) + ' 元');
		};
		$amount.on('keyup', onAmountChange).on('change', onAmountChange);
		// 创建"赠送理由"输入框
		var $reason = $box.createInput({
			name: 'reason',
			type: 'textarea',
			placeholder: '不超过50个字',
		});
		// 创建"确认按钮"
		$confirmBtn = $box.createButton('赠送').on('click', function() {
			var amount = parseInt($amount.val());
			var reason = $.trim($reason.val());
			if (amount <= 0) {
				alert('赠送金额必须大于0');
				return false;
			};
			if (reason.length > 50) {
				alert('赠送理由不得超过50字');
				$reason.val(reason.substr(0, 50));
				return false;
			};

			var msg = "确定赠送 " + (amount / 100).toFixed(2) + " 元给用户【" + user.nickname + "】\r\n理由:" + reason;

			if (!confirm(msg)) {
				$box.hide();
				return false;
			}

			var post = {
				uid: user.id,
				amount: amount,
				reason: reason,
			}
			var url = urlPrefix + 'user/presrent';
			$.post(url, post, function(rtn) {
				var rtn = API.checkResponse(rtn);
				if (rtn.error === 0) {
					alert('赠送成功');
					location.reload();
				}
				$box.hide();
			});
		});
		// 组建box
		$box.title('赠送水费')
			.addLi('用户', [$nickname])
			.addLi('赠送金额', [$amount, $fen, $yuan])
			.addLi('赠送理由', [$reason])
			.addLi('&nbsp;', [$confirmBtn]);
		return {
			show: function(_user) {
				user = _user
				$nickname.text(user.nickname);
				$box.show();
			},
		};
	})();
	// 增加'操作'列
	table.addCols([{
		index: -1,
		th: function($th) {
			$th.text('操作')
		},
		td: function($td, $tr) {
			var $tdList = $tr.find('td');
			var user = {
				id: Number($tdList.eq(index.uid).text()),
				nickname: $.trim($tdList.eq(index.nickname).text()),
			};
			// 查看用户详情
			(function($td, table) {
				var url = urlPrefix + 'user/detail?uid=' + user.id;
				var $btnList = $('<div>').appendTo($td).addClass('vBtnList');

				var $firstBtn = table.createBtn().text('查看').appendTo($td).appendTo($btnList)
					.on('click', function() {
						winOpen(url);
					})
					// var $subBtn = table.createBtn().css({
					// 	display:'none',
					// 	zIndex:'9999',
					// });
					// $subBtn.clone(true).text('买水订单').appendTo($btnList)
					// 	.on('click', function() {
					// 		winOpen(url + '#buy');
					// 	})
					// $subBtn.clone(true).text('充值订单').appendTo($btnList)
					// 	.on('click', function() {
					// 		winOpen(url + '#buy');
					// 	})
					// var $subList = $btnList.find('button:hidden');
					// var onMouseover = false;
					// var timer=null;
					// $btnList.mouseover(function(e) {
					// 	onMouseover = true;
					// 	setTimeout(function(){
					// 		if(onMouseover){
					// 			$subList.slideDown();
					// 			$btnList.addClass('vBtnList-on');
					// 		}
					// 	},200)

				// }).mouseleave(function() {
				// 	$subList.slideUp();
				// 	$btnList.removeClass('vBtnList-on');
				// 	onMouseover = false;
				// 	if(timer){
				// 		clearTimeout(timer);
				// 	} 
				// })


			})($td, table)

			// table.createBtn().text('赠送').appendTo($td).on('click', function() {
			// 	PresrentBox.show(user);
			// });
			// table.createBtn().text('清空余额').appendTo($td).on('click', function() {
			// 	var url = urlPrefix + 'user/empty_balance?uid=' + user.id;
			// 	var $balance = $tdList.eq(index.balance);
			// 	var balance = parseInt($balance.text() / 100);
			// 	if (!confirm('确定清除用户[' + user.nickname + ']余额(' + balance + ')?')) {
			// 		return false;
			// 	}
			// 	$.post(url, function(rtn) {
			// 		var rtn = JSON.parse(rtn);
			// 		if (rtn.msg) {
			// 			alert(rtn.msg);
			// 		};
			// 		if (rtn.error === 0) {
			// 			alert('清除用户余额成功!');
			// 			$balance.text(0).css({
			// 				background: 'antiquewhite'
			// 			});
			// 		} else {
			// 			alert('操作失败');
			// 		}
			// 	});
			// });
		}
	}]);
	// "合并用户"按钮
	fBtns.addBtn(function($btn) {
		$btn.text('合并用户').on('click', function() {
			var url = urlPrefix + 'user/combine';
			var winID = 'userCombine';
			winOpen(url, winID, '1000');
		});
	});
}
/**
 * 充值订单控制器
 */
function rechargeOrderCtrl() {
	var index = {};
	index.amount = getThIndexByText('充值金额');
	index.tradeState = getThIndexByText('订单状态');
	index.tradeID = getThIndexByText('商户订单号');
	index.orderID = getThIndexByText('订单ID');
	var queryOrderUrl = location.origin + urlPrefix + 'recharge/wx_order_query?id=';
	table.$tbody.each(function(_index, e) {
		var $tdList = $(e).find('td');
		$tdList.eq(index.amount).addClass('amount');
		var $tradeState = $tdList.eq(index.tradeState)
		var tradeState = $tradeState.text();
		tradeState = $.trim(tradeState);

		if (tradeState != '支付成功') {
			var $btn = table.createBtn().text('更新').appendTo($tdList.last());
			$btn.on('click', function() {
				var orderID = $tdList.eq(index.orderID).text();
				orderID = $.trim(orderID);
				var url = queryOrderUrl + orderID;
				$.get(url, function(rtn) {
					var rtn = JSON.parse(rtn);
					if (rtn.error === undefined && rtn.error != 0) {
						console.log(rtn);
						return false;
					}
					alert(rtn.msg);
					if (rtn.msg != tradeState) {
						$tradeState.text(rtn.msg).css('color', 'red');;
					}

				})
			})
		}
	})
}
/**
 * 买水订单控制器
 */
function buyOrderCtrl() {
	var index = {};
	index.amount = getThIndexByText('金额');
	table.$tbody.each(function(_index, e) {
		var $tdList = $(e).find('td');
		$tdList.eq(index.amount).addClass('amount');
	});
}
/**
 * 设备列表控制器
 */
function devIndexCtrl() {
	var lastCol = {
		index: -1,
		th: function($th) {
			$th.text('操作');
		},
		td: function($td, $tr, trData) {
			var id = trData.id;
			var type = trData.type;
			table.createBtn()
				.appendTo($td)
				.text('修改')
				.on('click', function() {
					var url = urlPrefix + 'dev/detail?did=' + id;
					var winId = 'devDetail' + id;
					winOpen(url, winId);
				});
		}
	};
	var firstCol = {
		index: 0,
		th: function($th) {
			var $checkbox = table.createCheckbox();
			$checkbox.appendTo($th).on('click', function() {
				table.$tbody.find('input[type="checkbox"]')
					.prop('checked', $checkbox.prop('checked'))
					.trigger('change');
			});
		},
		td: function($td, $tr, trData) {
			var id = trData.id;
			var $checkbox = table.createCheckbox()
			$checkbox.appendTo($td)
				.on('change', function() {
					if ($checkbox.prop('checked')) {
						$tr.addClass('checked-tr');
					} else {
						$tr.removeClass('checked-tr');
					}
				});
		}
	}
	table.addCols([firstCol, lastCol]);
	// 批量修改学校
	(function() {
		// 选中的ID列表
		var idList = [];
		// 创建提示框
		var $batchUpdateSchoolBox = new TipsBox();
		// 提示框的学校select框
		var $schoolSelect = $('#searchForm').find('select[name="schoolID"]').clone(true, true);
		// 提示框的设备列表
		var $devList = $('<div></div>')
			.css({
				width: '180px',
				wordBreak: 'break-word',
				float: 'left',
			});
		// 提示框的确认按钮
		var $confirmBtn = $batchUpdateSchoolBox.createButton('确定').on('click', function() {
			var schoolID = $schoolSelect.val();
			schoolID = parseInt(schoolID);
			if (schoolID <= 0) {
				alert('请选择学校');
				return false;
			}
			if (idList.length <= 0) {
				alert('请选择设备');
				return false;
			}
			var data = {
				schoolID: schoolID,
				idList: idList,
			};
			url = urlPrefix + 'dev/batchUpdateSchool';
			$.post(url, data, function(json) {
				var rtn = API.checkResponse(json);
				if (rtn.msg) {
					alert(rtn.msg);
				}
				location.reload();
			});

		});
		$batchUpdateSchoolBox.addLi('设备ID', [$devList])
			.addLi('学校', [$schoolSelect])
			.addLi('&nbsp;', [$confirmBtn]);
		// 显示"批量修改学校"按钮
		$('<button class="scbtn" type="button">批量修改学校</button>')
			.css({
				position: 'absolute',
				right: '100px',
				width: '100px',
			})
			.appendTo($('.sarchbtn'))
			.on('click', function() {
				$checked = table.$tbody.find(':checked');
				if ($checked.length <= 0) {
					alert('请勾选要修改的设备!');
					return false;
				}
				$checked.each(function(index, e) {
					var $tr = $(e).parents('tr');
					var id = $tr.find('td').eq(1).text();
					id = parseInt(id);
					idList.push(id);
				});
				console.log(idList);
				$devList.text(idList.join(' '));
				$batchUpdateSchoolBox.show();

			});
	})() //end 批量修改学校=====================================
}